/**
 * 操作按钮处理
 */
function initOperat(){
	$(".operat").each(function(){
	    var operat = $(this);
	    operat.find(".action").on("mouseenter DOMNodeInserted",function(){
	        operat.removeClass("hidden").addClass("show_munu");
	        var offset = operat.offset();
	        var height = operat.find(".action").height();
	        var action_width = operat.find(".action").outerWidth();
	        var menu_select_width = operat.find(".menu_select").outerWidth();
	        
	        if(offset.top+operat.find(".menu_select").height()+height < $(window).height()){
	        	if(offset.left+menu_select_width< $(window).outerWidth()) operat.find(".menu_select").offset({left:offset.left,top:(Math.floor(offset.top)+1+height)});
	        	else operat.find(".menu_select").offset({left:(offset.left+action_width-menu_select_width),top:(Math.floor(offset.top)+1+height)});
	            operat.find(".action").removeClass("top").addClass("bottom");
	        }else{
	            if(offset.left+menu_select_width< $(window).outerWidth()) operat.find(".menu_select").offset({left:offset.left,top:Math.ceil(offset.top)-1-operat.find(".menu_select").height()});
	            else operat.find(".menu_select").offset({left:(offset.left+action_width-menu_select_width),top:Math.ceil(offset.top)-1-operat.find(".menu_select").height()});
	            operat.find(".action").removeClass("bottom").addClass("top");
	        }
	        
	    });
	    operat.on("mouseleave",function(){
	        operat.removeClass("show_munu").addClass("hidden");
	    })
	})
}

/**
 * 工具栏选择
 * @param name
 * @param obj
 * @returns {Boolean}
 */
function tools_select(name,obj){
	$('input[name=\''+name+'\']').prop('checked',$(obj).hasClass('icon-checkbox-unchecked'));
	$(obj).toggleClass('icon-checkbox-unchecked');
	return false;
}

/**
 * 工具栏提交
 * @param obj
 * @returns {Boolean}
 */
function tools_submit(obj){
	var form = $('form:first');
	var confirm_flag = false;
	if(obj!=undefined){
		if(obj['form']!=undefined) form = $(obj['form']);
		if(obj['action']!=undefined)form.attr('action',obj['action']);
		if(obj['method']!=undefined){
			if(obj['method']=='get' || obj['method']=='post'){
				form.attr('method',obj['method']);
			}
			else form.attr('method','post');
		}
		else form.attr('method','post');
		if(form.attr('method')=='get'){
			var pattern = /(\w+)=(\w+)/ig;
			var parames = {};
			obj['action'].replace(pattern, function(a, b, c){parames[b] = c;});
			for(par in parames)form.append("<input type='hidden' name='"+par+"' value='"+parames[par]+"'>");
		}
		if(obj['msg']!=undefined) confirm_flag = true;
	}
	var select_id = "id";
	if(obj['select_id']!=undefined) select_id = obj['select_id'];
	if(confirm_flag){		
        $.dialog.confirm('你确认删除操作吗？删除后无法恢复！', function(){
			if($("input[name='"+select_id+"[]']:checked").size()>0){
				$selcted_ids = new Array();
				$("input[name='"+select_id+"[]']:checked").each(function(){
					$selcted_ids.push($(this).val());	
				})
	            $.ajax({
	                url:obj['action'],
	                cache:false,
	                dataType:'json',
	                type:'POST',
	                data:{id:$selcted_ids.join(',')},
	                success:function(msgObj){
	                	if(msgObj.status==1){
		                	window.location.href=msgObj.url;
	                	}else{
                            $.dialog.alert(msgObj.info);
	                	}
	                    return false;
	                }
	            });
			}
			else art.dialog.tips("<p class='warning'>没有选择任何项目，无法删除</p>");
		});
	}else{
		form.submit();
	}
	return false;
}

//重新刷新页面，使用location.reload()有可能导致重新提交
function reloadPage(win) {
    var location = win.location;
    location.href = location.pathname + location.search;
}

//高级筛选插件
//此插件必需与artdialog联合使用 
(function($){
	$.fn.Condition = function(o){
		o = $.extend({data:[],okVal:'保存'}, o || {});
		var fields_select = "";
		if(o.data!=undefined){
			var data = o.data;
			for(i in data){
				fields_select += "<option value='"+i+"'>"+data[i]['name']+"</option>";
			}
		}
		if(fields_select!='')fields_select = "<select class='rounded' style='line-height:28px;height:28px; margin-top:2px;'><option value='noselect'>添加筛选字段</option>"+fields_select+"</select>";
		$.dialog({id:'conditionDialog',zIndex:100,title:'高级查询',padding:"6px",fixed: true,lock:true,resize: false,content:'<div id="condition_dialog" style="width:600px; height:336px; " ><div class="tools_bar clearfix"> <span class="icon-plus fl"> '+fields_select+'</span> </div><div style="overflow: auto;width:600px; height:250px;"><table id="condition_table" class="default form2"><tr><th width="80">关系</th><th>字段名称</th><th width="100">比较关系</th><th>比较值</th><th width="60">操作</th></tr></table></div><div class="tc mt10"><a href="javascript:;" class="button btn" id="condition_create">'+o.okVal+'</a></div></div>'});
		//检测表达式
		function check_condition(condition)
	    {
	    	var reg = /^(\S+--\S+--\S+--\S+__)*(\S+--\S+--\S+--\S+)$/i;
	        return reg.test(condition);
	    }
		if(o.input!=undefined){
			var ini_data = $(o.input).val();
			if(ini_data!='' && check_condition(ini_data)){
				ini_data = ini_data.split('__');
				for(var i in ini_data){
					var value = '';
					var item = ini_data[i].split('--');
					if(o.data[item[1]]!=undefined)
					{
						if(o.data[item[1]]['values']!=undefined){
							var values = o.data[item[1]]['values'];
							for(var k in values){
								if(k==item[3]) 
									value += "<option value='"+k+"' selected='selected'>"+values[k]+"</option>";
								else
									value += "<option value='"+k+"' >"+values[k]+"</option>";
							}
							if(value!='') value = "<select>"+value+"</select>";
						}
						if(value=='') value = "<input value='"+item[3]+"'/>";
					var str = '<tr><td><select><option value="and">并且</option><option value="or">或者</option></select></td><td><input type="hidden" value="'+item[1]+'">'+o.data[item[1]]['name']+'</td><td><select> <option value="eq"> = </option> <option value="ne"> != </option> <option value="lt"> < </option> <option value="le"> <= </option> <option value="gt"> > </option> <option value="ge"> >= </option> <option value="ct">包含</option> <option value="nct">不包含</option> </select></td><td>'+value+'</td><td><a class="icon-close" href="javascript:;">删除</a></td></tr>';
					var reg = new  RegExp('(value=\\"'+item[0]+'\\")',"i");
					str = str.replace(reg,'$1 selected="selected"');
					var reg = new  RegExp('(value=\\"'+item[2]+'\\")',"i");
					str = str.replace(reg,'$1 selected="selected"');
					$("#condition_table").append(str);

					} 
					
				}
				bindEvent();
			}
			
		}

		//添加事件的绑定
		$("#condition_dialog .icon-plus select").on("change",function(){
			var current = $(this).find("option:selected");
			var value = '';//'<input value=""/>';43
			if(o.data[current.val()]['values']!=undefined){
				var values = o.data[current.val()]['values'];
				for(var i in values){
					value += "<option value='"+i+"'>"+values[i]+"</option>";
				}
				if(value!='') value = "<select>"+value+"</select>";
			}
			if(value=='') value = "<input value=''/>";
			if(current.val()!='noselect'){
				$("#condition_table").append('<tr><td><select><option value="and">并且</option><option value="or">或者</option></select></td><td><input type="hidden" value="'+current.val()+'">'+current.text()+'</td><td><select> <option value="eq"> = </option> <option value="ne"> != </option> <option value="lt"> < </option> <option value="le"> <= </option> <option value="gt"> > </option> <option value="ge"> >= </option> <option value="ct">包含</option> <option value="nct">不包含</option> </select></td><td>'+value+'</td><td><a class="icon-close" href="javascript:;"> 删除</a></td></tr>');
					bindEvent();
			}
			$(this).val('noselect');//重置select
		})

		$("#condition_create").on("click",function(){
			var con = '';
			$("#condition_table tr:has(td)").each(function(i){
				var item = $("select,input",$(this));
				var str = item.eq(0).val()+'--'+item.eq(1).val()+'--'+item.eq(2).val()+'--'+item.eq(3).val()+'__';
				if(item.eq(3).val()!='' && con.indexOf(str)==-1)con += str;
			});
			con = con.replace(/__$/g,'');
			if(o.input!=undefined){
				if(con!=''){
					$(o.input).val(con);
					$.dialog({id:'conditionDialog'}).close();
                    $.dialog.tips("<p class='success'>筛选条件保存成功！('关系值'为空的选项自动忽略)</p>");
					if(o.callback != undefined) o.callback(con);
				}
				else{
                    $.dialog.tips("<p class='warning'>所有【关系值】为空，筛选无效！</p>");
				}
			}
		})
		
		//操作按钮事件绑定
		function bindEvent(){
		  $("#condition_dialog .icon-close").off();
		    $("#condition_dialog table .icon-close").on("click",function(){
		      $(this).parent().parent().remove();
		    });
		}
		bindEvent();	
	};  
})(jQuery);



/**
 * ajax删除操作
 */
function doAjaxDel(){
	$(".doDel").click(function(){
	    var uri = $(this).attr("data-uri");
	    var that = this;
        $.dialog.confirm("你确认删除操作吗？删除后无法恢复！", function () {
	        $.ajax({
	            url:uri,
	            cache:false,
	            dataType:'json',
	            type:'POST',
	            data:{},
	            success:function(msgObj){
	            	if(msgObj.status==1){
                        $.dialog.tips('删除成功!');
	                    $(that).closest('tr').remove();     		
	            	}else{
                        $.dialog.alert(msgObj.info);
	            	}
	                return false;
	            }
	        });
	    }, function () {
	    });
	});	
}

$(document).ready(function(){
	
	/**
	 * 操作按钮初始化
	 */
	initOperat();
	
	/**
	 * ajax删除操作
	 */	
	doAjaxDel();

	//iframe页面f5刷新
	$(document).on('keydown', function (event) {
	    var e = window.event || event;
	    if (e.keyCode == 116) {
	        e.keyCode = 0;

	        var $doc = $(parent.window.document),
	            iframe = $doc.find('#iframe_default');
	        try{
	            if (iframe[0]!=undefined&&iframe[0].contentWindow) {
	                //common.js
	                reloadPage(iframe[0].contentWindow);
	            }else{
	            	window.location.reload();
	            }
	        }catch(err){}
	        //!ie
	        return false;
	    }
	});
	
	/**
	 * tab标签切换
	 */
	$('#conf_menu li').click(function(){
		$(this).closest('#conf_menu').find('li').removeClass('current');
		$(this).addClass('current');
		var id = $(this).attr('id')+'ig';
		$("form .tab_label").hide();
		$('#'+id).show();
	});
	
    //切换
    $('.pointer').on('click', function() {
        var url = $(this).closest('table').attr("data-uri");
        var img    = this,
        s_val  = ($(img).attr('data-value'))== 0 ? 1 : 0,
        s_name = $(img).attr('data-field'),
        s_id   = $(img).attr('data-id'),
        s_src  = $(img).attr('src');
        s_msg = ($(img).attr('data-value'))== 0 ? '启用' : '禁用';
        $.ajax({
            url:url,
            cache:false,
            dataType:"json",
            data: {id:s_id, field:s_name, val:s_val},
            type:"POST",
            beforeSend:function(){
                $("#J_ajax_loading").stop().removeClass('ajax_error').addClass('ajax_loading').html("提交请求中，请稍候...").show();
            },
            error:function(){
                $("#J_ajax_loading").addClass('ajax_error').html("AJAX请求发生错误!").show().fadeOut(5000);
            },
            success:function(msgObj){
                $("#J_ajax_loading").hide();
                if(msgObj.status == '1'){
                    $("#J_ajax_loading").removeClass('ajax_error').addClass('ajax_success').html(msgObj.info).show().fadeOut(5000);
                    if(s_src.indexOf('icon_0')>-1) {
                            $(img).attr({'src':s_src.replace('icon_0','icon_1'),'data-value':s_val,'title':s_msg,'alt':s_msg});
                    } else {
                          $(img).attr({'src':s_src.replace('icon_1','icon_0'),'data-value':s_val,'title':s_msg,'alt':s_msg});
                    }
                }else{
                    $("#J_ajax_loading").removeClass('ajax_success').addClass('ajax_error').html(msgObj.info).show().fadeOut(5000);
                }
            }
        });
    });


    //切换
    $('.menu_select').find('.operation').on('click', function() {
        var url = $(this).attr("data-uri");
        $.ajax({
            url:url,
            cache:false,
            dataType:"json",
            type:"POST",
            beforeSend:function(){
                $.dialog.tips("提交请求中，请稍候...");
            },
            error:function(){
                $.dialog.alert("AJAX请求发生错误...");
            },
            success:function(msgObj){
                if(msgObj.status == '1'){
                    $.dialog.tips(msgObj.info);
                }else{
                    $.dialog.alert(msgObj.info);

                }
            }
        });
    });


	//右侧配置按钮点击
    $('span.bar-btn').click(function () {
        $('ul.bar-list').toggle('fast');
    });
    
    //列表样式控制
    $('.list tr:odd').addClass('odd');  
    $('.list tr:even').addClass('even');
    $('.list tr').hover( 
        function(){
            $(this).addClass('activity'); 
        },
        function(){
            $(this).removeClass('activity'); 
        }
    );
    
    //分页控制
    $('.pg_select').change(function(){
        var page = $(this).val();
        var pram = $(this).attr('data-param');
        var url = $(this).attr('data-uri')+'/'+page+pram;
        window.location.href = url;
    })
    
    //图片预览
    $('.view_pic').on('click', function(){
        var title = $(this).attr('title');
        var data_uri = $(this).attr('data-uri');
        var that = $(this, window.top.document);
        $.dialog({
            id:'view_pic', 
            title:title, 
            padding:'',
            resize: false,
            drag: false,
            width:'50%', 
            lock:true
        });
        var dialog = $.dialog.get('view_pic');
        dialog.content('<img src="'+data_uri+'"/>');
        /*
        $.get(data_uri, function(html){
            dialog.content('<img src="'+data_uri+'"/>');
        });*/        
    });
});

/**
 * 图片上传
 * @param string server_url 图片处理路径 如：http://2014.ci.com/demo/demo/upload_image
 * @param string clickID 点击元素的ID
 * @param string inputID 上传成功之后，获取信息的元素ID
 */
function upload_image(server_url,clickID,inputID){

    var // 优化retina, 在retina下这个值是2
    ratio = window.devicePixelRatio || 1,

    // 缩略图大小
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio,

    // Web Uploader实例
    uploader;

	// 初始化Web Uploader
	uploader = WebUploader.create({
	
	    // 自动上传。
	    auto: true,
	
        //是否压缩
        compress:false,

	    // swf文件路径
	    //swf: '<?php echo URLPRE.'static/public/Lib/webuploader/js/Uploader.swf';?>',
	
	    // 文件接收服务端。
	    server: server_url,
	
	    // 选择文件的按钮。可选。
	    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
	    pick: '#'+clickID,
	
	    // 只允许选择文件，可选。
	    accept: {
	        title: 'Images',
	        extensions: 'gif,jpg,jpeg,bmp,png,ico',
	        mimeTypes: 'image/*'
	    }
	});
	
	// 文件上传成功，给item添加成功class, 用样式标记上传成功。
	uploader.on('uploadSuccess',function( file,ret ) {
	    if(ret.status==0){
	        alert(ret.info);         
	    }else{
	        $('#'+inputID).val(ret.info);
	    }
	    $( '#'+file.id ).addClass('upload-state-done');
	});	
}



/**
 * 图片上传进度
 * @param string server_url 图片处理路径 如：http://2014.ci.com/demo/demo/upload_image
 * @param string clickID 点击元素的ID
 * @param string inputID 上传成功之后，替换图片路径
 * @param string replaceId 要替换图片盒子
 */
function upload_image_2(server_url,clickID,inputID,replaceId,SRCPREFIX){

    var // 优化retina, 在retina下这个值是2
        ratio = window.devicePixelRatio || 1,

    // 缩略图大小
        thumbnailWidth = 100 * ratio,
        thumbnailHeight = 100 * ratio,

    // Web Uploader实例
        uploader;

    // 初始化Web Uploader
    uploader = WebUploader.create({

        // 自动上传。
        auto: true,

        // swf文件路径
        //swf: '<?php echo URLPRE.'static/public/Lib/webuploader/js/Uploader.swf';?>',

        // 文件接收服务端。
        server: server_url,

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#'+clickID,

        // 只允许选择文件，可选。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png,ico',
            mimeTypes: 'image/*'
        }
    });


    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {

        $('#'+replaceId).attr('src','/static/public/images/load.gif');
        var $progress = $( '#'+replaceId).next('span') ;
        $progress.empty().html('完成'+Math.floor(percentage * 100) + '%...');
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on('uploadSuccess',function( file,ret ) {
        if(ret.status==0){
            alert(ret.info);
        }else{
			var prefix = '';
			if(typeof(SRCPREFIX) != "undefined"){
				prefix =SRCPREFIX;
			}
			$('#'+inputID).val(prefix+ret.info);
            $('#'+replaceId).attr('src',prefix+ret.info);
			$('#'+replaceId).attr('data-uri',prefix+ret.info);
        }
        $( '#'+file.id ).addClass('upload-state-done');
        $( '#'+replaceId).next('span').empty();
    });
}



/**
 * 文件上传
 * @param string server_url 文件处理路径 如：http://2014.ci.com/demo/demo/upload_image
 * @param string clickID 点击元素的ID
 * @param string inputID 上传成功之后，获取信息的元素ID
 */
function upload_file(server_url,clickID,inputID){
    WebUploader.create({
        auto: true,
        server: server_url,
        pick: '#'+clickID,
    }).on('uploadSuccess', function( file,ret ) {
        if(ret.status==0){
            alert(ret.info);
        }else{
            $('#'+inputID).val(ret.info);
        }
        $( '#'+file.id ).addClass('upload-state-done');
    });
}

/**
 * 增加一行表格
 * @param obj
 * @param type
 */
var addrowdirect = 0;
var addrowkey = 0;
function addrow(obj, type) {
    var table = obj.parentNode.parentNode.parentNode.parentNode;
    if(!addrowdirect) {
        var row = table.insertRow(obj.parentNode.parentNode.rowIndex);
    } else {
        var row = table.insertRow(obj.parentNode.parentNode.rowIndex + 1);
    }
    var typedata = rowtypedata[type];
    for(var i = 0; i <= typedata.length - 1; i++) {
        var cell = row.insertCell(i);
        cell.colSpan = typedata[i][0];
        var tmp = typedata[i][1];
        if(typedata[i][2]) {
            cell.className = typedata[i][2];
        }
        tmp = tmp.replace(/\{(n)\}/g, function($1) {return addrowkey;});
        tmp = tmp.replace(/\{(\d+)\}/g, function($1, $2) {return addrow.arguments[parseInt($2) + 1];});
        cell.innerHTML = tmp;
    }
    addrowkey ++;
    addrowdirect = 0;
}

/**
 * 删除一行表格
 * @param obj
 */
function deleterow(obj) {
    var table = obj.parentNode.parentNode.parentNode.parentNode;
    var tr = obj.parentNode.parentNode;
    table.deleteRow(tr.rowIndex);
}

function _showdistrict(elems, changelevel, code, did) {
    var getdid = function(elem) {
        var op = elem.options[elem.selectedIndex];
        return op['did'] || op.getAttribute('did') || '0';
    };

    var levelhtml = [
        '<option value="-1" did="-1">选择洲</option>',
        '<option value="-1" did="-1">选择国家</option>',
        '<option value="-1" did="-1">选择省</option>',
        '<option value="-1" did="-1">选择市</option>',
        '<option value="-1" did="-1">选择区/县</option>'
    ];
    var id = -1;
    if(changelevel == 1 && elems[0] && document.getElementById(elems[0])){
        id = getdid(document.getElementById(elems[0]));
    }else if(changelevel == 2 && elems[1] && document.getElementById(elems[1])){
        id = getdid(document.getElementById(elems[1]));
    }else if(changelevel == 3 && elems[2] && document.getElementById(elems[2])){
        id = getdid(document.getElementById(elems[2]));
    }else if(changelevel == 4 && elems[3] && document.getElementById(elems[3])){
        id = getdid(document.getElementById(elems[3]));
    }
    if(code){
        id = code;
    }
    if(id != -1 || changelevel == 0){
        if(changelevel == 0){
            id = 0;
        }
        $.ajax({
            url:district_url + id,
            method:'GET',
            dataType:'json',
            success: function(msg){
                var s = '';
                for(var i in msg){
                    if(in_array(msg[i].id, did)){
                        s += '<option selected="selected" did="'+msg[i].id+'" value="'+msg[i].id+'">'+msg[i].name+'</option>';
                    }else{
                        s += '<option did="'+msg[i].id+'" value="'+msg[i].id+'">'+msg[i].name+'</option>';
                    }
                }
                if(document.getElementById(elems[changelevel])){
                    $('#'+elems[changelevel]).html(levelhtml[changelevel] + s);
                /*document.getElementById(elems[changelevel]).innerHTML = levelhtml[changelevel] + s;*/
                    _showdistrict(elems, changelevel+1, null, did);
                }
            }
        });
    }else{
        if(document.getElementById(elems[changelevel])){
            /*document.getElementById(elems[changelevel]).innerHTML = levelhtml[changelevel];*/
            $('#'+elems[changelevel]).html(levelhtml[changelevel]);
            _showdistrict(elems, changelevel+1, null, did);
        }
    }
}
function in_array(needle, haystack) {
    if(typeof needle == 'string' || typeof needle == 'number') {
        for(var i in haystack) {
            if(haystack[i] == needle) {
                return true;
            }
        }
    }
    return false;
}
var dist = '';
var sel = 0;
function add_dist(obj){
    dist ++;
    var ct = 'continent' + dist;
    var co = 'country' + dist;
    var pr = 'province' + dist;
    var ci = 'city' + dist;
    var ar = 'area' + dist;

    var distary_str = '[\''+ct+'\', \''+co+'\', \''+pr+'\', \''+ci+'\', \''+ar+'\']';
    var html = '<div class="mb10">';
    html+=
        '<select name="t[continent][]" id="'+ct+'" onchange="_showdistrict('+distary_str+', 1)">' +
        '<option value="-1" did="-1">选择洲</option>' +
        '</select> ' +
        '<select name="t[country][]" id="'+co+'" onchange="_showdistrict('+distary_str+', 2)">' +
        '<option value="-1" did="-1">选择国家</option>' +
        '</select> ' +
        '<select name="t[province][]" id="'+pr+'" onchange="_showdistrict('+distary_str+', 3)">' +
        '<option value="-1" did="-1">选择省</option>' +
        '</select> ' +
        '<select name="t[city][]" id="'+ci+'" onchange="_showdistrict('+distary_str+', 4)">' +
        '<option value="-1" did="-1">选择市</option>' +
        '</select> ' +
        '<select name="t[area][]" id="'+ar+'"' +
        '<option value="-1" did="-1">选择区/县</option>' +
        '</select>' +
        '</div>';
    $(html).insertBefore($(obj));
    if(!sel){
        _showdistrict([ct, co, pr, ci, ar], 0);
    }
}

function del_dist(obj){
    var div = $(obj).parent().find('div');
    if(div.length>1){
        div.last().remove();
    }
}



    $(function(){

        // 放大图片
        $('#DataBox').find('img').mouseover(function(){

            var top =  $(this).offset().top;
            var width = $(this).width()*3;
            var height = $(this).height()*3;
            var left =  $(this).offset().left;
            var src = $(this).attr('src');
            var html = '<img src="'+src+'" width="'+width+'" height="'+height+'">';
            $('#popup').append(html).css({"position":"absolute","top":top,"left":left});

        })


        $('#popup').mouseleave(function(){

            $('#popup').empty();
        })
    })



